#include <iostream>
#include <vector>
#include <queue>

using namespace std;

/**
 * Definition for a binary tree node.
 */
struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};


class Solution {
public:
    /**
     * @brief 这题不适合用递归方式，因为很难判定 leaf 比如：
     *    1  1 的右边为 nullptr
     *   /
     *  2
     */
    bool hasPathSum(TreeNode* root, int targetSum) {
        if (!root) return false;
        queue<tuple<TreeNode*, int>> q;
        q.push({root, root->val});

        while (!q.empty()) {
            tuple<TreeNode*, int> node_val = q.front(); q.pop();
            TreeNode* node = get<0>(node_val);
            int currSum = get<1>(node_val);

            // Make sure it is the leaf
            if (!node->left && !node->right && currSum == targetSum) {
                return true;
            }

            if (node->left) q.push({node->left, currSum + node->left->val});
            if (node->right) q.push({node->right, currSum + node->right->val});
        }
        return false;
    }
};
